﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

namespace BingDownloader
{
    static class BingHelper
    {
        static string bing = "http://www.bing.com/";
        static string bingInternational = "http://www.bing.co.jp";
        static string bingUS = "http://www.bing.com/?mkt=en-US";

        private static string RetrieveWebPageAsString(string query)
        {
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
            
            // execute the request
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse) request.GetResponse();
            }
            catch (Exception /*e*/)
            {                
                throw new ApplicationException("Either Bing Server is Down or you don't have Internet Access or your computer is behind a firewall!");
            }
           
            string fileContent = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                fileContent = sr.ReadToEnd();
            }

            return fileContent;            
        }

        public static Bitmap RetriveBitmapAtLocation(string query)
        {
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);

            // execute the request
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)
                request.GetResponse();
            }
            catch (Exception /*e*/)
            {
                throw new ApplicationException("Either Bing Server is Down or you don't have Internet Access or your computer is behind a firewall!");                
            }

            return new Bitmap(response.GetResponseStream());            
        }

        private static string GetBingImageFile(string websiteAddress)
        {
            string fullWebpageText = RetrieveWebPageAsString(websiteAddress);            
            string findStr = "var g_img={url:'";
            int startIndex = fullWebpageText.IndexOf(findStr);
            startIndex += findStr.Length;
            int lastIndex = fullWebpageText.IndexOf('\'', startIndex);

            string imgPath = fullWebpageText.Substring(startIndex, lastIndex - startIndex);
            imgPath = imgPath.Replace(@"\", "");

            return bing + imgPath;
        }

        public static string GetBingInternationalImageFile()
        {
            return GetBingImageFile(bingInternational);
        }

        public static string GetBingUSImageFile()
        {
            return GetBingImageFile(bingUS);
        }
    }
}